/**
 * 要素编辑工具
 */
import {Modify,DoubleClickZoom,Select} from "ol/interaction"
import WKT from 'ol/format/WKT';
//全局的地图对象
let Map = null
// 编辑后的坐标
let Feature =null
// 鼠标点击标识
let flag = false
export default class olModify{
    constructor(map){
        Map = map
    }
    /**
     * 开启编辑
     * @param {*} option 
     * endModify：绘制结束后的回调函数，返回绘制要素的坐标信息
     */
    modify(option){
      
        //创建一个交互选择对象
        let select = new Select({
            wrapX: false
        });
        Map.addInteraction(select);
        //创建一个交互修改对象
        let modify = new Modify({
            //设置要素为交互选择对象所获取的要素
            features: select.getFeatures()
        });
        Map.addInteraction(modify);
        //开启捕捉交互功能
        modify.on("modifyend",function (e) {
            let features=e.features.array_;
            Feature = features[0]
        });
        
        Map.on('click', function (evt) {
            if(!flag){
                flag = true
            }else{
                flag =false
                Map.removeInteraction(select);
                Map.removeInteraction(modify);
                if(option&&option.endModify&&Feature){
                    var format = new WKT();
                    option.endModify({
                        feature:Feature,
                        coordinate:Feature.getGeometry().getCoordinates(),
                        wkt:format.writeFeature(Feature)
                    })
                } 
                Feature =null
            }    
        });
        // 禁止鼠标双击事件
        const dblClickInteraction = Map.getInteractions().getArray().find(interaction => {
          return interaction instanceof DoubleClickZoom;
        });
        Map.removeInteraction(dblClickInteraction);
    }
   
}